package com.mouse.remind;//

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ze.commontool.NetHelper;
import com.ze.familydayverpm.userinfo.UserInfoManager;


import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class AlarmUpdateService extends Service{
	
	Context mContext;
	
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		Log.d(this.getClass().getSimpleName(),"onCreate()");
		super.onCreate();
		mContext = this;
	}

	private static final int MSG_ON_COMPLETE = 1;
	/**
     * 该 Handler 用于将后台线程回调转发到 UI 线程。
     */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_ON_COMPLETE:
            	Intent i = new Intent(getApplicationContext(), AlarmBootService.class);
	        	startService(i); 
                break;
    
            default:
                break;
            }
        }
    };
    
    public void request(final String date) {
        
        new Thread() {
            @Override
            public void run() {
                try {
                	List<AlarmModel> tempList = getAlarmListDay(date);

        			if(tempList != null && tempList.size() > 0){
        				Database.init(getApplicationContext());
        				boolean hasAdd = Database.createAll(tempList);
        				if (hasAdd) {
        					mHandler.obtainMessage(MSG_ON_COMPLETE, 1).sendToTarget();
						}
        			}
                } catch (Exception e) {
                }
            }
        }.start();
    }
	
	class GetAlarmListTask extends AsyncTask<Object, Object, String>{
	    String date;   
		List<AlarmModel>  tempList;
		boolean hasAdd = false;
		
		public GetAlarmListTask(String date) {
			this.date = date;
		}
		
		@Override
		protected String doInBackground(Object... params) {
			tempList = getAlarmListDay(date);

			if(tempList != null && tempList.size() > 0){
				Database.init(getApplicationContext());
				hasAdd = Database.createAll(tempList);
			}
			return null;
		}
		
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (hasAdd) {
				Intent i = new Intent(getApplicationContext(), AlarmBootService.class);
	        	startService(i); 
			}
		}
		
	}
	
	private List<AlarmModel> getAlarmListDay(String date) {
		//String jsonStr = WebTools.getDateByHttpClient(Urls.getAlarmListDay(date));
		String jsonStr = NetHelper.getResponByHttpClient(Urls.getAlarmListDay(date
				,UserInfoManager.getInstance(mContext).getItem("m_auth").getValue()));
		Log.v("mouse", jsonStr);
		List<AlarmModel> data = new ArrayList<AlarmModel>();
		AlarmModel alarm;
		
		if (jsonStr == null || jsonStr.equals("")) {
			return null;
		}
		try{
			JSONObject resultData = new JSONObject(jsonStr);
			int error = resultData.getInt("error");
			if(error == 0){
				JSONObject dataObj = resultData.getJSONObject("data");
				JSONArray listArr = dataObj.getJSONArray("list");
				int num = listArr.length();
				JSONObject temp;
				 
				for(int i=0; i<num; i++){
					temp = listArr.getJSONObject(i);
					alarm = new AlarmModel();
					alarm.setAlarmid(temp.getString("id"));
					alarm.setSubject(temp.getString("subject"));
					alarm.setYear(temp.getString("year"));
					alarm.setMonth(temp.getString("month"));
					alarm.setDay(temp.getString("day"));
					alarm.setWday(temp.getString("wday"));
					alarm.setTime(temp.getString("time"));
					alarm.setUid(temp.getString("uid"));
					alarm.setTouids(temp.getString("touids"));
					alarm.setRepeatday(temp.getString("repeatday"));
					alarm.setIdtype(temp.getString("idtype"));
					
					ArrayList<User> users = new ArrayList<User>();
					JSONArray calendarto = temp.getJSONArray("calendarto");
					int toNum = calendarto.length(); 
					for(int j=0; j<toNum; j++){
						JSONObject userObj = calendarto.getJSONObject(j);
						User user = new User();
						user.setUid(userObj.getString("uid"));
						user.setUsername(userObj.getString("username"));
						user.setName(userObj.getString("name"));
						user.setAvatar(userObj.getString("avatar"));
						user.setVipstatus(userObj.getString("vipstatus"));
						
						users.add(user);
					}
					alarm.setUserList(users);
					
					data.add(alarm);
				}
			}else {
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return data;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		Database.deactivate();
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(this.getClass().getSimpleName(),"onStartCommand()");
		
		Calendar nowCalendar = Calendar.getInstance();
	    int year = nowCalendar.get(Calendar.YEAR);
	    int month = nowCalendar.get(Calendar.MONTH)+1;
	    int day = nowCalendar.get(Calendar.DAY_OF_MONTH);
        String date = year+"-"+month+"-"+day;
        
        //new GetAlarmListTask(date).execute();
        request(date);
        
		return START_NOT_STICKY;
	}

}
